import time
import json
import random
from multiprocessing import Process, Pipe


def doAlu(times, childConn, clientId):
    a = random.randint(10, 100)
    b = random.randint(10, 100)
    temp = 0
    for i in range(times):
        if i % 4 == 0:
            temp = a + b
        elif i % 4 == 1:
            temp = a - b
        elif i % 4 == 2:
            temp = a * b
        else:
            temp = a / b
    # print(times)
    childConn.send(temp)
    childConn.close()
    return temp


def alu(times, parallelIndex):
    per_times = int(times / parallelIndex)
    threads = []
    childConns = []
    parentConns = []
    for i in range(parallelIndex):
        parentConn, childConn = Pipe()
        parentConns.append(parentConn)
        childConns.append(childConn)
        t = Process(target=doAlu, args=(per_times, childConn, i))
        threads.append(t)
    for i in range(parallelIndex):
        threads[i].start()
    for i in range(parallelIndex):
        threads[i].join()

    results = []
    for i in range(parallelIndex):
        results.append(parentConns[i].recv())
    return str(results)


def handle(req):
    st = time.time()
    """handle a request to the function
    Args:
        req (str): request body
    """
    jsonObj = json.loads(req)
    loopTime = jsonObj['loopTime']
    parallelIndex = jsonObj['parallelIndex']
    res = alu(loopTime, parallelIndex)

    et = time.time()
    return (et - st) * 1000


if __name__ == "__main__":
    defaultLoopTime = 10000000
    defaultParallelIndex = 100
    res = handle(json.dumps({
        "loopTime": defaultLoopTime,
        "parallelIndex": defaultParallelIndex
    }))
    print(type(res))
    print(res)
